package demo4.controller;

import demo4.mapper.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import demo4.mapper.IUserMapper;
import demo4.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

import java.util.Scanner;


@Component
public class UserController {
    @Autowired
    private IUserMapper userMapper;
    public void start()  {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要操作的序号");
        System.out.println("用户系统");
        System.out.println("1.注册");
        System.out.println("2.登录");
        System.out.println("3.修改密码");
        System.out.println("4.用户列表");

        int num = sc.nextInt();
        switch (num) {
            case 1:
                userReg();
                break;
            case 2:
                userLogin();
                break;
            case 3:
                System.out.println("修改密码");
                break;
            case 4:
                userList();
                break;

        }
    }

    private void userLogin(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String name = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();
        User user = userMapper.selectUsername(name);
        if(user != null){
            if(user.getPassword().equals(password)){
                System.out.println("登录成功，欢迎【"+user.getNickname()+"】回来");
            }else{
                System.out.println("密码错误");
            }
        }else{
            System.out.println("用户不存在");
        }
    }

    private void userReg(){
        System.out.println("UserController:开始处理用户注册...");
        User user = new User();
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入用户名");
            String username = scanner.nextLine();
            if(userMapper.selectUsername(username)==null){
                user.setUsername(username);
                break;
            }
            System.out.println("用户名已存在");
        }

        System.out.println("请输入密码:");
        user.setPassword(scanner.nextLine());
        System.out.println("请输入昵称:");
        user.setNickname(scanner.nextLine());
        System.out.println("请输入年龄:");
        user.setAge(scanner.nextInt());

        //实际在这里还要进行必要的验证，比如:有没有没输入的，有没有不合法的，是否重复用户

        int num = userMapper.insert(user);
        System.out.println(num>0?"注册成功":"注册失败");

        System.out.println("UserController:注册完毕");
    }

    public void userList(){
        List<User> list = userMapper.selectAll();
        for(User user:list){
            System.out.println(user);
        }
    }

}